<template>
  <div>
    <el-table-form ref="form" class="form" :model="query">
      <el-form-item :table-form-merge="1" class="merge-item">
        <el-select v-model="type1" style="width: 170px; margin-right: 2px;">
          <el-option label="客户电话" value="csmPhone" />
          <el-option label="客户名称" value="csmName" />
          <el-option label="申请人" value="userName" />
        </el-select>
        <el-input v-model.trim="csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="type2" style="width: 170px; margin-right: 2px;">
          <el-option label="欠瓶时间" value="startDt" />
          <el-option label="实际归还时间" value="endDt" />
        </el-select>
        <el-date-picker
          v-model="date"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="所属机构:" class="merge-item">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData
          }"
          :tree-params=" {
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props:{
              value:'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="状态:">
        <el-select v-model="query.status" filterable clearable>
          <el-option v-for="(l,i) in enumMap" :key="i" :label="l.desc" :value="l.value" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-checkbox v-model="query.todo" style=" margin-right: 10px; margin-left: 10px;">待处理</el-checkbox>
        <el-button type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button type="primary" icon="el-icon-plus" @click="addBottle">新增欠瓶</el-button>
        <el-button type="primary" icon="el-icon-download" :loading="$loadingPlugin.exportFile" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-el-height-adaptive-table="{bottomOffset:10}"
      v-loading="$loadingPlugin.fetchData"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
      @expand-change="clickExpand"
    />
    <addBottle ref="addBottle" @refresh="refresh" />
    <detailbottle ref="detail" />
  </div>
</template>

<script>
  import { parseTime } from '@/utils'
  import { oweBottleList, queryMap, oweBottleUpdate, oweBottleExport, oweBottleDetail } from '@/api'

  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'

  export default {
    name: 'rentManage',
    components: {
      addBottle: require('./components/add.vue').default,
      detailbottle: require('./components/details.vue').default
    },
    data() {
      return {
        expandData: [],
        actionColWidth: 80,
        type1: 'csmPhone',
        type2: 'startDt',
        csmText: '',
        date: [new Date((new Date()).getFullYear(), (new Date()).getMonth(), 1), new Date()], // 当前月第一天和当前日  默认值
        query: {
          status: '',
          checked: false
        },
        searchParams: {},
        treeData: [],
        enumMap: [],

        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'exportDomain'
      ]),
      column: function() {
        return [
          { type: 'expand', render: (h, { row, $index }) => {
            return (
                  <div>
                    {this.expandData[row.id] && this.expandData[row.id].map(item => (
                      <div style='padding-left: 40px; padding-top: 7px;; padding-bottom: 7px;'>
                        <span>
                          <span><span class='bold'>商品类型：</span>{item.gtName}</span> |&nbsp;&nbsp;
                          <span><span class='bold'>商品名称：</span>{item.goodsName}</span> |&nbsp;&nbsp;
                          <span><span class='bold'>数量：</span>{item.gdCount}</span>
                        </span>
                      </div>
                    ))}
                  </div>
                )
          } },
          {
            type: 'index'
          },
          {
            prop: 'userName',
            label: '申请人'
          },
          {
            prop: 'csmCode',
            label: '客户编码'
          },
          {
            prop: 'csmName',
            label: '客户名称'
          },
          {
            prop: 'csmPhone',
            label: '联系电话',
            width: 110
          },
          {
            prop: 'csmAddress',
            label: '客户地址',
            width: 150
          },
          {
            prop: 'gasDesc',
            label: '欠瓶描述',
            width: 120
          },
          {
            prop: 'status',
            label: '状态',
            render: (h, { row }) => <span style={this.getColor(row.status)}>{this.enumMap.find(l => row.status === l.value) ? this.enumMap.find(l => row.status === l.value).desc : ''}</span>
          },
          {
            prop: 'startDt',
            label: '欠瓶时间',
            width: 160,
            render: (h, { row }) => <span>{ row.startDt && parseTime(row.startDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'planBackDt',
            label: '预计还瓶时间',
            width: 160,
            render: (h, { row }) => <span>{ row.planBackDt && parseTime(row.planBackDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'endDt',
            label: '实际归还时间',
            width: 160,
            render: (h, { row }) => <span>{ row.endDt && parseTime(row.endDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'recGPBMIDS',
            label: '气瓶号',
            width: '150'
          },
          {
            prop: 'recChipIDS',
            label: '芯片号',
            width: '150'
          },
          {
            prop: 'orgName',
            label: '责任机构',
            width: '180'
          },
          {
            prop: 'auditor',
            label: '审核人'
          },
          {
            prop: 'auditDt',
            label: '审核时间',
            width: 160,
            render: (h, { row }) => <span>{ row.auditDt && parseTime(row.auditDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            label: '操作',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
                <div class='handle'>
                  {row.status === 1 && <el-link underline={false} size='mini' onClick={() => this.handle(row, 2)}> 审核</el-link>}
                  {(row.status === 2 || row.status === 3) && <el-link underline={false} size='mini' onClick={() => this.handle(row, 4)}>还瓶确认 </el-link>}
                  { row.status === 1 && <el-link underline={false} size='mini' type='danger' onClick={() => this.handle(row, -1)}>  作废 </el-link>}
                  <el-link underline={false} size='mini' onClick={() => this.details(row, $index)}>欠瓶明细 </el-link>
                </div>
              )
            }
          }
        ]
      }
    },
    created() {
      this.getTreeData()
      this.getStatusMap()
    },
    mounted() {
      this.$watch('query.todo', (val) => {
        this.fetchData({})
      })
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.orgName,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.orgSNNo = value.orgSNNo
      },
      search() {
        if (this.date) {
          this.fetchData({})
        } else {
          this.$message.error('请选择查询时间段')
        }
      },
      // 新增
      addBottle() {
        this.$refs.addBottle.open()
      },
      // 欠瓶明细
      details(row) {
        this.$refs.detail.open(row)
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const params = {
          currentPage,
          pageSize,
          orgSNNo: this.query.orgSNNo,
          status: this.query.status,
          todo: Boolean(this.query.todo)
        }
        params[this.type1] = this.csmText
        if (this.date && this.date.length === 2) {
          params[this.type2] = this.date[0]
          params[`${this.type2}End`] = this.date[1]
        }
        const res = await oweBottleList(this._getQuery(params))
        this.searchParams = params
        if (res.success) {
          this.tableData.data = res.data.rows
        }
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      refresh() {
        this.fetchData({})
      },
      // 操作
      async handle(row, num) {
        // 审核 2
        // 作废 -1
        // 还瓶 4
        if (!num) return
        const params = {
          id: row.id,
          status: num
        }
        var txt = ''
        switch (num) {
        case 2:txt = '审核'
               break
        case -1:txt = '作废'
                break
        case 4:txt = '还瓶'
               break
        }
        this.$confirm(`确认${txt}?`, '提示', {
          type: 'warning'
        }).then(async() => {
          const res = await oweBottleUpdate(params)
          if (res.success) {
            this.$message.success('操作成功')
            this.fetchData({})
          }
        })
      },
      getColor(val) {
        var colorObj = {
          1: 'color:#ff0000;',
          2: 'color:#cc33ff;',
          3: 'color:#389E0D;',
          4: 'color:#01999f;',
          5: 'color:#330066;'
        }

        return colorObj[val]
      },
      async getStatusMap() {
        const res = await queryMap({ enumName: 'UserOrgGasRecordStatus' })
        this.enumMap = res.data
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          oweBottleExport({
            paramInfo: _this._getQuery(this.searchParams),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      async clickExpand(row, expandedRows) {
        if (expandedRows.length > 0) {
          const item = expandedRows.find(item => item.id === row.id)
          if (item) {
            this.$set(this.expandData, item.id, [])
            const res = await oweBottleDetail({
              id: row.id
            })
            if (res.data && res.data.detailList) this.$set(this.expandData, item.id, JSON.parse(res.data.detailList))
          }
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .form {
    display: flex;
    flex-wrap: wrap;
  }
  .handle {
    display: flex;
  }
</style>
